<template>
	<!-- <om-page title="登录" style="
    position: absolute;
    bottom: 0;
    left: 0;
    top: 0;
    width: 100%;
"> -->
	<view>
		<view class="nlogo om-btn-color" v-if="csaccount && csaccount == account">{{ name.substring(name.length-2) }}</view>
		<!-- <image class="logo" v-if="csaccount && csaccount == account" :src="imgSrc ? imgSrc : '/static/images/others/favicon.png'" ></image> -->
		<image class="logo" v-else src="/static/images/others/favicon.png"></image>
		<view class="text-xxl des" v-if="csaccount && csaccount == account">{{ '你好，' + name }}</view>
		<view class="text-xxl des" v-else>欢迎使用OM系统</view>
		<view class="content">
			<om-wing-blank>
				<!-- #ifndef H5 -->
				<!-- <view class="text-lg text-gray padding-top">{{loginOrgName}}</view> -->
				<!-- #endif -->
				<view class="input-group" style="margin-top: 10px;">
					<view class="input-row border">
						<text class="title" style="font-size: 16px;">手机号</text>
						<m-input class="m-input" type="text" clearable :focus="accountFocus" v-model="account"
							placeholder="请输入手机号"></m-input>
					</view>
					<view class="input-row border">
						<text class="title" style="font-size: 16px;">密码</text>
						<m-input type="password" displayable v-model="password" placeholder="请输入密码"></m-input>
					</view>
					<!-- <view>
						payloadData2:{{zpayloadData2}}
					</view>
					<view>payload:{{payload}}</view>
					<view>orgSite:{{orgSite}}</view>
					<view>url:{{url}}</view>
					<view>mobile:{{account}}</view>
					<view>authKey:{{authKey}}</view>
					<view>error:{{error}}</view> -->
					
				</view>
				<!-- <view class="check-box"><i class="check" :class="check == true ? 'selected' : ''" @tap="selectCheck"></i><a @tap="showPrivacy" class="checkdes">隐私政策和用户协议</a></view> -->
				<view class="btn-row" style="margin-top: 0;">
					<button type="primary" class="primary" @tap="bindLogin">登录</button>
				</view>
				<view class="flex justify-end">
					<view class="cu-tag radius bg-grey light" style="font-size:14px;">
						<navigator url="/pages/login/version-info/version-info">版本记录</navigator>
					</view>
					<!-- #ifdef APP-PLUS-->
					<!-- <view class="cu-tag radius bg-grey light" style="font-size:14px;">
						<navigator url="/pages/login/scancode/scancode">修改网址</navigator>
					</view> -->
					<!-- #endif -->
					<!-- <view class="cu-tag radius bg-grey light" style="margin-right: 10px;font-size:14px;">
						<view  @click="forgetPwdClick">忘记密码</view>
					</view> -->
				</view>
				<view>
					<view class="check-box"><i class="check" :class="check == true ? 'selected' : ''" @tap="selectCheck"></i>我已阅读并同意<a @tap="showAgree" class="checkdes">用户协议</a>、<a @tap="showPrivacy" class="checkdes">隐私政策</a></view>
				</view>
			</om-wing-blank>
		</view>
		
		<uni-popup  id="popup" ref="popup" :type="'center'">
			<view class="popup-cotent padding">
				<view class="margin popup-tip" style="font-size: 14px;">
					请选择你要登录的组织
				</view>
				<view  class="popup-item padding"  v-for="(item,index) of orgSites" :key="index" @click="selectOrg(item,index)">
					<text class="sname">
						{{item.orgName}}
					</text>
					<i class="check pcheck" :class="{'selected': checkIndex == index}"></i>
					<!-- <uni-icons :size="20" class="uni-icon-wrapper" color="#bbb" type="arrowright" /> -->
				</view>
				<view class="margin flex justify-end">
					<text class="margin-top om-color" style="margin-right: 15px;" @click="selectOrgHandle">
						确定
					</text>
					<text class="margin-top om-color" @click="closePop">
						取消
					</text>
				</view>
			</view>
		</uni-popup>
		
	</view>
	<!-- </om-page> -->
</template>

<script>
	import {
		ignoreHtml,
		getUrl,
		errorModal,
		getAutoLoginTimes
	} from '@/static/js/common.js'
	import md5 from '@/static/js/md5.js';
	const form = require("@/static/js/formValidation.js")
	import service from '@/service.js';
	import {mapState, mapActions} from 'pinia';
	import { useLoginUserStore } from '@/stores/login-user.js';
	import orgMap from '@/static/json/orgList.json'
	const app = getApp();
	export default {
		data() {
			return {
				zpayloadData2: '',
				orgSite:'',
				payload:'',
				url:'',
				error:'',
				loginOrgName: '',
				stateurl:'',
				account: '',//
				password: '',
				authKey: '',
				accountFocus: false,
				check: false,
				orgSites:[],
				name: '',
				csaccount: '',
				imgSrc: '',
				checkItem: {},
				checkIndex: -1,
			};
		},
		onLoad(e) {
			let _that = this;
			uni.getStorage({
				key: "ORG_SITE",
				success(res) {
					if (!res.data) {
						uni.navigateTo({
							url: '/pages/login/confirm-appurl/confirm-appurl'
						})
					}
				},
				fail(res){
					uni.navigateTo({
						url: '/pages/login/confirm-appurl/confirm-appurl'
					})
				}
			})
			
			
			let num = getAutoLoginTimes();
			if (num > 1) {
				return
			}
			_that.clearToken();
			var msgStr = uni.getStorageSync("payloadData2");
			_that.zpayloadData2 = msgStr;
			if(msgStr){
				_that.pushLogin()
			}else{
				if (e.account) {
					_that.account = e.account
				}
				// #ifdef APP-NVUE || APP-PLUS || APP-PLUS-NVUE
				let orgSite = uni.getStorageSync("ORG_SITE")
				if (orgSite && orgSite.site) {
					if (orgSite.site.endsWith("/")) {
						app.globalData.url = orgSite.site
					} else {
						app.globalData.url = orgSite.site + "/"
					}
					_that.loginOrgName = orgSite.name
				}
				// #endif
						
				let token = _that.om.getToken();
				if (token) {
					_that.account = token.name;
					_that.password = token.pwd;
					_that.authKey = token.key;
					_that.check = true
					if(!_that.authKey){
						_that.bindLogin();
					} else {
						_that.hlogin();
					}
					
				} else {
					// #ifdef H5
					_that.accountFocus = true
					if (!_that.subUrl) {
						let hostname = window.location.hostname
						if (hostname) {
							let org = orgMap.orgList[hostname]
							if (org) {
								_that.setSubUrl(org.om_url)
								_that.setOrgName(org.orgname)
							}
						}
					}
					// #endif
				}
			}
		},
		onShow() {
			let _that = this;
			uni.getStorage({
				key: "ORG_SITE",
				success(res) {
					if (!res.data) {
						uni.navigateTo({
							url: '/pages/login/confirm-appurl/confirm-appurl'
						})
					}
				},
				fail(res){
					uni.navigateTo({
						url: '/pages/login/confirm-appurl/confirm-appurl'
					})
				}
			})
			
			//#ifndef H5
			let num = getAutoLoginTimes();
			if (num > 1 || !_that.account || !_that.password) {
				_that.checkAppVersion();
			}
			//#endif
			uni.getStorage({
				key: "ORG_LOGIN",
				success(res) {
					if (res.data) {
						let obj = JSON.parse(res.data)
						_that.csaccount = obj.mobile
						_that.account = obj.mobile
						_that.name =  obj.name
						_that.imgSrc = obj.imgSrc
					}
				}
			})
		},
		computed: {
			...mapState(useLoginUserStore, [
				'forcedLogin',
				'hasLogin', 
				'orgName', 
				'subUrl'
			])
		},
		methods: {
			...mapActions(useLoginUserStore, [
				'login',
				'setOrgName',
				'setSubUrl',
				'clearToken',
				'setToken'
			]),
			pushLogin(){
				var _that = this;
				var msgStr = uni.getStorageSync("payloadData2");
				_that.zpayloadData2 = "pushLogin: " + msgStr;
				var msg = JSON.parse(msgStr);
				if(msg.payload){
					var payload = null;
					if(typeof msg.payload === 'string'){
						payload = JSON.parse(msg.payload)
					} else {
						payload = msg.payload;
					}
					var orgSite = {
						site: payload.orgSite,
						name: payload.orgName
					};
					uni.setStorageSync('ORG_SITE', orgSite);
					
					if (orgSite && orgSite.site) {
						_that.orgSite = JSON.stringify(orgSite);
						if (orgSite.site.endsWith("/")) {
							app.globalData.url = orgSite.site
						} else {
							app.globalData.url = orgSite.site + "/"
						}
						_that.loginOrgName = orgSite.name
					}
					_that.payload = JSON.stringify(payload);
					_that.url = app.globalData.url
					_that.account = payload.mobile;
					_that.authKey = payload.authKey;
					_that.check = true
					if(!app.globalData.url){
						_that.error = "app.globalData.url 为空";
						return
					}
					_that.hlogin();
				}
			},
			forgetPwdClick(){
				let _that = this
				_that.om.request(
					'sms/hasSms'
				).then(res=>{
					if(!res.value.succeed && res.value.msg){
						errorModal(_that,'提示信息',res.value.msg)
					}else{
						uni.navigateTo({
							url:'../forgetpwd/forgetpwd'
						})
					}
				})
			},
			//#ifndef H5
			checkAppVersion() {
				//判断是否有新版本进行更新
				plus.runtime.getProperty(plus.runtime.appid, function(widgetInfo) {
					let appUrl = 'https://zst.om909.com/';
					uni.request({
						url: appUrl + 'version/checkVersion.do',
						data: {
							version: widgetInfo.version,
							name: widgetInfo.name,
							platform: uni.getSystemInfoSync().platform,
							serverUrl: app.globalData.url
						},
						success: (res) => {
							if (res.data.succeed) {
								let data = res.data.value;
								let fileSize = data.fileSize;
								if (data.update && data.url) {
									//热更新版本或者安卓版本
									if ((data.url.substring(data.url.length - 3, data.url.length) ==
											'wgt') || (data.url.substring(data.url.length - 3, data.url
											.length) == 'apk')) {
										if (data.msg) {
											uni.showModal({
												title: '版本更新',
												content: data.msg,
												showCancel: false,
												success(res) {
													if (res.confirm) {
														plus.nativeUI.closeWaiting();
														plus.runtime.quit();
													}
												}
											})
										} else {
											uni.showModal({
												title: '版本更新',
												content: '当前存在新版本，请进行更新！本次更新大小为' + fileSize,
												showCancel: false,
												success(res) {
													if (res.confirm) {
														plus.nativeUI.showWaiting("下载更新文件...");
														uni.downloadFile({
															url: appUrl + data.url,
															success: (
																downloadResult) => {
																	if (downloadResult
																		.statusCode ===
																		200) {
																		plus.nativeUI
																			.closeWaiting();
																		plus.nativeUI
																			.showWaiting(
																				"正在安装文件..."
																				);
																		plus.runtime
																			.install(
																				downloadResult
																				.tempFilePath, {
																					force: false
																				},
																				function() {
																					plus.nativeUI
																						.closeWaiting();
																					plus.runtime
																						.restart();
																				},
																				function(
																					e
																					) {
																					plus.nativeUI
																						.closeWaiting();
																				});
																	}
																},
															fail: (msg) => {
																plus.nativeUI
																	.closeWaiting();
																_that.om.toast(
																	'网络异常！');
															}
														});
													}
													if (res.cancel) {
														plus.nativeUI.closeWaiting();
													}
												}
											})
										}
									}
									//苹果版本
									if (data.url.substring(data.url.length - 3, data.url.length) ==
										'ipa') {
										if (data.msg) {
											uni.showModal({
												title: '版本更新',
												content: data.msg,
												showCancel: false,
												success(res) {
													if (res.confirm) {
														plus.nativeUI.closeWaiting();
														plus.runtime.quit();
													}
												}
											})
										} else {
											uni.showModal({
												title: '版本更新',
												content: '当前存在新版本，请前往AppStore更新版本！',
												showCancel: true,
												success(res) {
													if (res.confirm) {
														let appleId = 1542963362
														plus.runtime.launchApplication({
															action: `itms-apps://itunes.apple.com/cn/app/id${appleId}?mt=8`
														}, function(e) {
															console.log(
																'Open system default browser failed: ' +
																e.message);
														});
													}
												}
											})
										}
									}
								}
							} else {
								_that.om.toast(res.data.msg);
							}
						}
					})
				});

			},
			// #endif
			selectOrg(item,index){
				let _that = this;
				_that.checkItem = item
				_that.checkIndex = index
			},
			selectOrgHandle(){
				let _that = this;
				let item = _that.checkItem
				if(_that.checkIndex != -1){
					_that.stateurl = item.orgSite;
					_that.loginOrgName = item.orgName;
					if (!_that.stateurl) {
						return;
					}
					if(!_that.stateurl.endsWith("/")){
						_that.stateurl = _that.stateurl + "/"
					}
					uni.request({
						url: _that.stateurl+'version/check.do',
						data:{
							loginType: service.getAppType()
						},
						success: (res) => {
							_that.closePop();
							if(res.data.value == 'SUCCESS'){
								uni.setStorageSync('ORG_SITE', {
									site: _that.stateurl,
									name: item.orgName
								});
								app.globalData.url = _that.stateurl
								_that.toLogin()
							}else{
								_that.om.toast('网址有误，请联系系统管理员修改OM平台的组织网址！');
							}
						},
						fail: (msg) => {
							_that.closePop();
							_that.om.toast('网址有误，请联系系统管理员修改OM平台的组织网址！');
						}
					})
				}else{
					_that.om.toast('请选择组织后再进行操作！');
				}
				
			},
			closePop(){
				this.$refs.popup.close()
			},
			// APP平台自动登录
			hlogin(){
				let _that = this
				const data = {
					mobile: _that.account
				};
				uni.showLoading({
					title: '登录中'
				});
				
				_that.om.request('loginCenter/henter', data, 'post', true, {
					header: {
						'authKey': _that.authKey
					}
				}).then(res => {
					uni.hideLoading()
					if (res.succeed) {
						_that.setToken(res.value.token,"", _that.authKey);
						_that.login(res.value.accountInfo);
						let obj = {
							mobile: res.value.accountInfo.mobile,
							name: res.value.accountInfo.username,
							imgSrc: res.value.accountInfo.avatar
						}
						uni.setStorageSync('ORG_LOGIN', JSON.stringify(obj));
						if (this.hasLogin) {
							uni.switchTab({
								url: '/pages/main/main/main'
							});
						}
					} else {
						_that.error = "loginCenter/henter 返回值"+res.msg
						_that.om.toast(res.msg);
						_that.accountFocus = true
					}
				});
			},	
			bindLogin() {
				let _that = this;
				let formData = {account:_that.account,password:_that.password};
				let rules = [
					{name:"account",rule:["required","isMobile"],msg:["请输入手机号","请输入正确的手机号码"]},
					{name:"password",rule:["required"],msg:["请输入密码"]},
				];
				let msg = form.validation(formData,rules);
				if(msg) {
					errorModal(null,"错误提示",msg);
					return 
				}
				
				if(_that.check != true){
					_that.om.toast('请阅读并勾选“隐私政策和用户协议”');
					return;
				}
				
				// #ifdef APP || APP-PLUS
				let orgSite = uni.getStorageSync('ORG_SITE');
				if(orgSite && orgSite.site){
					_that.stateurl = orgSite.site
					app.globalData.url = _that.stateurl
					_that.toLogin(true)
				}else{
					_that.om.mateRequest('integrate/getLoignSite', {
						phone: _that.account,
						password: md5.hex_md5(_that.password.toLowerCase())
					},'POST').then(res => {
						if(res.success){
							let orgSites = res.data;
							if(orgSites && orgSites.length){
								if(orgSites.length == 1){
									_that.stateurl = orgSites[0].orgSite
									uni.setStorageSync('ORG_SITE', {
										site: _that.stateurl,
										name: orgSites[0].orgName
									});
									app.globalData.url = _that.stateurl
									_that.toLogin()
								}else{
									_that.orgSites = orgSites
									_that.$refs.popup.open();
								}
							} else {
								_that.om.toast('用户名或密码错误！');
							}
						}else{
							// uni.reLaunch({
							// 	url: "/pages/login/scancode/scancode"
							// })
							uni.reLaunch({
								url: "/pages/login/confirm-appurl/confirm-appurl"
							})
						}
					})
				}
				// #endif
				// #ifdef H5
				_that.toLogin();
				// #endif
			},
			toLogin(againFlag){
				let _that = this
				const data = {
					mobile: _that.account,
					password: md5.hex_md5(_that.password.toLowerCase())
				};
				uni.showLoading({
					title: '登录中'
				});
				_that.om.request('loginCenter/enter', data, 'post', false).then(res => {
					if (res.succeed) {
						_that.setToken(res.value.token)
						_that.toMain(res.value.accountInfo);
						// _that.toMain(res.value);
						let obj = {
							mobile: res.value.accountInfo.mobile,
							name: res.value.accountInfo.username,
							imgSrc: res.value.accountInfo.avatar
						}
						uni.setStorageSync('ORG_LOGIN', JSON.stringify(obj));
					} else {
						if(againFlag){
							uni.removeStorageSync('ORG_SITE')
							_that.bindLogin();
						} else {
							uni.hideLoading()
							_that.om.toast(res.msg);
							_that.accountFocus = true
						}
					}
				});
			},
			toMain(sessionInfo) {
				if (!sessionInfo || !sessionInfo.userid) {
					this.om.clearToken();
					this.om.toast("登录失败，请检查用户名或密码是否正确！")
				} else {
					this.login(sessionInfo);
					this.om.setToken(this.account, this.password);
					if (this.hasLogin) {
						if (sessionInfo.orgid) {
							uni.switchTab({
								url: '/pages/main/main/main'
							});
						} else {
							uni.navigateTo({
								url: "/pages/login/orgins/orgins"
							});
						}
					}
				}
			},
			showPrivacy() {
				uni.navigateTo({
			 	url: '/pages/login/privacypolicy/privacy-policy'
				});
			},
			showAgree(){
				uni.navigateTo({
				    url: '/pages/login/privacypolicy/user-agreement'
				});
			},
			selectCheck() {
				this.check = !this.check
			},
		}
	};
</script>

<style scoped>
	/* .forgetPwd{
		text-align: right;
		font-size: 14px;
		padding-top: 15px;
		text-decoration: none;
		color: #0faeff;
	} */
	.check-box {
		margin-top: 10px;
		position: relative;
		overflow: hidden;
		font-size: 16px;
	}

	.check {
		float: left;
		margin: 4px 4px 0 10px;
		width: 16px;
		height: 16px;
		display: block;
		background: url("");
		background-size: 16px 16px;
	}

	.check.selected {
		background: url("") no-repeat;
		background-size: 16px 16px;
	}

	.checkdes {
		/* float: left; */
		color: #0faeff;
		line-height: 20px;
	}
	
	.nlogo{
		width: 46px;
		height: 46px;
		line-height: 46px;
		border-radius: 8px;
		margin: 30px 0 10px 8px;
		color: #FFF;
		text-align: center;
		font-size: 16px;
	}
	
	.logo{
		width: 46px;
		height: 46px;
		border-radius: 8px;
		margin: 30px 0 10px 8px;
	}
	
	.des{
		margin-left: 8px;
	}
	
	.popup-item{
		text-align: left;
	}
	
	.sname{
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
		width: 250px;
	}
	
	.pcheck{
		width: 18px;
		margin: 3px;
	}
</style>
